package com.xzit.aop;

import com.xzit.aop.config.RiskAreaConfig;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
@Component
public class RiskCheckerAspect {

    @Autowired
    private RiskAreaConfig config;

    @Around("execution(* com.xzit.aop.impl.TravelService.travel(..))")
    public Object checkRisk(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        String name = (String) args[0];
        String from = (String) args[1];
        String to = (String) args[2];

        if (config.isRiskArea(from)) {
            System.out.printf("【高风险提醒】出发地 [%s] 属于高风险地区，禁止用户 [%s] 出行！%n", from, name);
            return null;
        }

        Object result = joinPoint.proceed();

        if (config.isRiskArea(to)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.printf("【高风险日志】用户 [%s] 从 [%s] 前往高风险地区 [%s]，出发时间：%s%n", name, from, to, time);
        }

        return result;
    }
}
